package inventory;

import factory.ItemFactory;
import item.EquipableItem;
import item.TakeableItem;

import java.util.ArrayList;
import java.util.HashMap;

import loadsave.Memento;
import loadsave.loadsaveobject.Iterator;
import loadsave.loadsaveobject.LoadSaveCollectionComposite;
import loadsave.loadsaveobject.LoadSaveIndex;
import loadsave.loadsaveobject.LoadSaveObject;
import loadsave.loadsaveobject.LoadSaveObjectComposite;
import model.ModelObject;

public class Inventory extends ModelObject {

	private ArrayList<TakeableItem> itemList;
	
	public Inventory() {
		super("inventory");
		itemList = new ArrayList<TakeableItem>();
	}
	
	public Inventory(ArrayList<TakeableItem> list) {
		super("inventory");
		itemList = list;
	}
	
	/**
	 * Does not add null elements to the list 
	 * @param item
	 * @return boolean
	 */
	public boolean addItem(TakeableItem item) {
		if (item != null) {
			itemList.add(item);
			this.notifyObservers();
			return true;
		}
		else {
			return false;
		}
	}
	
	public int getSize() {
		return itemList.size();
	}
	
	public boolean contains(TakeableItem item) {
		return itemList.contains(item);
	}
	
	public TakeableItem removeItem(TakeableItem item) {
		int index = itemList.indexOf(item);
		TakeableItem itemx = itemList.remove(index);
		this.notifyObservers();
		return (itemx);
	}
	
	public TakeableItem getItem(int index) {
		return itemList.get(index);
	}


    public Memento getMemento() {
    	return new Memento() {

			@Override
			public LoadSaveObject getState() {
				LoadSaveObjectComposite toReturn = new LoadSaveObjectComposite("", "Inventory");
				LoadSaveObject lso = Inventory.super.getMemento().getState();
				Iterator<LoadSaveObject> i = lso.getIterator();
				for (i.init(); i.hasNext(); i.next()) {
					toReturn.add(i.getCurrKey().getValue(), i.getCurrVal());
				}
				LoadSaveCollectionComposite lsmc = new LoadSaveCollectionComposite("itemList", "ArrayList", "TakeableItem");
				int index = 0;
				for (TakeableItem it : itemList) {
					lsmc.add(new LoadSaveIndex(index++), it.getMemento().getState());
				}
				toReturn.add(lsmc.getName(), lsmc);
				return toReturn;
			}

			@Override
			public void restoreState(LoadSaveObject lso) {
				Inventory.super.getMemento().restoreState(lso);
				itemList = new ArrayList<TakeableItem>();
				Iterator<LoadSaveObject> i = lso.get("itemList").getIterator();
				for (i.init(); i.hasNext(); i.next()) {
					itemList.add((EquipableItem) ItemFactory.createTakeableItem(i.getCurrVal()));
				}
			}
    		
    	};
    }
	
}
